package com.itheima.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.core.domain.AjaxResult;
import com.itheima.common.utils.SecurityUtils;
import com.itheima.common.utils.bean.BeanUtils;
import com.itheima.server.Enum.ClueStatus;
import com.itheima.server.domain.*;
import com.itheima.server.dto.ChangeContractDto;
import com.itheima.server.dto.ContractPageDto;
import com.itheima.server.service.*;
import com.itheima.server.mapper.ContractMapper;
import com.itheima.server.vo.ContractDeatilsVo;
import com.itheima.server.vo.ContractVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author li
* @description 针对表【hk_contract(合同信息表)】的数据库操作Service实现
* @createDate 2025-09-04 20:51:02
*/
@Service
@Slf4j
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {
    // 0 待生效 1 生效
    private static final int CONTRACT_NOT_START = 0;
    private static final int CONTRACT_START = 1;

    //活动有效
    private static final int Valid = 2;
    //默认研发部门
    private static final Long DEPT_ID = 103L;

    @Autowired
    private CourseService courseService;
    @Autowired
    private ActiviteService activiteService;
    @Autowired
    private IBusinessService businessService;
    @Autowired
    private BusinessDetailService businessDetailService;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ClueService clueService;

    /**
     * 获取合同列表
     * @param dto
     * @return
     */
    public AjaxResult getPageContractList(ContractPageDto dto) {

        Page<Contract> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        String beginCreateTime = dto.getParams().get("beginCreateTime");
        String endCreateTime = dto.getParams().get("endCreateTime");

        wrapper.like( dto.getName() != null && dto.getName() != "" ,Contract::getName,dto.getName())
                .like( dto.getContractNo() != null && dto.getContractNo() != "" ,Contract::getContractNo,dto.getContractNo())
                .like( dto.getPhone() != null && dto.getPhone() != "" ,Contract::getPhone,dto.getPhone())
                .eq( dto.getSubject() != null ,Contract::getSubject,dto.getSubject())
                .eq(  dto.getCourseId() != null ,Contract::getCourseId,dto.getCourseId())
                .between(beginCreateTime != null && beginCreateTime != "" && endCreateTime != ""  && endCreateTime != null, Contract::getCreateTime, beginCreateTime, endCreateTime);


        Page<Contract> result = super.page(page, wrapper);
        long total = result.getRecords().size();
        List<Contract> rows = result.getRecords();
        ArrayList<ContractVo> contractVos = new ArrayList<>();

        for (Contract row : rows) {
            ContractVo contractVo = new ContractVo();
            BeanUtils.copyProperties(row, contractVo);
            contractVo.setOrder(row.getOrders());
            contractVos.add(contractVo);
        }

        AjaxResult ajax = new AjaxResult(200, "查询成功");
        ajax.put("total",total);
        ajax.put("rows",contractVos);
        ajax.put("params",null);

        return ajax;
    }

    /**
     * 添加合同
     * @param contract
     * @return
     */
    public boolean addContract(Contract contract) {
        Contract one = getOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getContractNo, contract.getContractNo()));
        if (ObjectUtils.isNotEmpty(one)){
            throw new RuntimeException("合同编号已存在");
        }

        //判断手机号是否存在
        Contract one1 = getOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getPhone, contract.getPhone()));
        if (ObjectUtils.isNotEmpty(one1)){
            throw new RuntimeException("手机号已存在");
        }

        //设置合同状态
        contract.setStatus(CONTRACT_START);
        //课程价格需要获取课程信息 来计算折扣
        Course course = courseService.getOne(Wrappers.<Course>lambdaQuery().eq(Course::getId, contract.getCourseId()));
        Double price = course.getPrice().doubleValue();

        //获取购买该课程的折扣信息
        Activite activite = activiteService.getOne(Wrappers.<Activite>lambdaQuery().eq(Activite::getId, contract.getActivityId()));

        //折扣
        Double discount = activite.getDiscount();
        //优惠券
        Integer vouchers = activite.getVouchers();

        //合同的金额
        Double orders =  null;
        //1 是折扣 2是代金券 先判断拿到的优惠卷是不是有效的
        if (activite.getStatus() == Valid ){
            //判断活动优惠的类型 1 是折扣 2是代金券
            if (activite.getType().equals(1)){
                orders = price * discount * 0.1;
            } else if (activite.getType().equals(2)){
                //优惠券
                orders = price - vouchers;
            }
        } else {
            //优惠卷和折扣都是无效的
            orders = price;
        }
        contract.setCoursePrice(price);
        contract.setOrders(orders);

        contract.setDiscountType(activite.getType()+"");

        //合同完成时间 默认是上传合同时间加上6个月
        contract.setFinishTime(LocalDateTime.now().plusMonths(6));
        //查询bussinessId
//        Business business = businessService.getOne(Wrappers.<Business>lambdaQuery().eq(Business::getSubject, contract.getSubject()));
//        contract.setBusinessId(Long.parseLong(business.getId().toString()));

        contract.setBusinessId(null);
        //查询部门id
        contract.setDeptId(DEPT_ID);

        contract.setCreateTime(new Date());
        contract.setUpdateTime(new Date());

        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setUpdateBy(SecurityUtils.getUsername());
        return super.save(contract);
    }


    @Override
    @Transactional
    public AjaxResult changeContract(Integer id, ChangeContractDto changeContractDto) {
        BusinessDetail businessDetail = businessDetailService.getById(id);
        Business business = businessService.getById(id);

        if (businessDetail != null|| business != null){
            Contract contract = new Contract();

            contract.setContractNo(changeContractDto.getContractNo());
            contract.setFileName(changeContractDto.getFileName());
            contract.setPhone(changeContractDto.getPhone());


            contract.setName(business.getName());

            if (business.getChannel()!= null){
                contract.setChannel(Integer.parseInt(business.getChannel()));
            }
            contract.setSubject(Integer.parseInt(business.getSubject()));

            if(businessDetail== null){
                contract.setActivityId(null);
            }else {
                if (businessDetail.getCourseId()!= null){
                    contract.setCourseId(Long.valueOf(businessDetail.getCourseId()));
                }
            }



            contract.setStatus(CONTRACT_START);
            contract.setBusinessId(Long.valueOf(business.getId()));

            //获取课程相关
            Course course = courseService.getOne(Wrappers.<Course>lambdaQuery().eq(Course::getId, contract.getCourseId()));

            if (course == null){
                contract.setCoursePrice(null);
            }else {
                contract.setCoursePrice(course.getPrice().doubleValue());
            }

            contract.setOrders(contract.getCoursePrice());
            contract.setDeptId(DEPT_ID);

            contract.setCreateTime(new Date());
            contract.setUpdateTime(new Date());
            contract.setFinishTime(LocalDateTime.now().plusMonths(6));
            contract.setCreateBy(SecurityUtils.getUsername());
            contract.setUpdateBy(SecurityUtils.getUsername());
            super.save( contract);
            //修改商机，线索转状态
            Clue clue = clueService.getOne(Wrappers.<Clue>lambdaQuery().eq(Clue::getName, business.getName()));
            if (clue != null){
                clue.setStatus(ClueStatus.CONTRACT.status.toString());
                clueService.updateById( clue);
            }
            business.setStatus(3);
            businessService.updateById(business);

            //设置owner为空
            UpdateWrapper<Business> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", business.getId());
            updateWrapper.set("owner", null);
            businessService.update(updateWrapper);



            return new AjaxResult(200,"添加成功");



        }


        return  new AjaxResult(500,"添加失败");
    }

    /**
     * 更新合同
     * @param contract
     * @return
     */
    public Boolean updateContract(Contract contract) {
//        Contract one = getOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getContractNo, contract.getContractNo()));
//        if (ObjectUtils.isNotEmpty(one)){
//            throw new RuntimeException("合同编号已存在");
//        }

        //课程价格需要获取课程信息 来计算折扣
        Course course = courseService.getOne(Wrappers.<Course>lambdaQuery().eq(Course::getId, contract.getCourseId()));
        Double price = course.getPrice().doubleValue();

        //获取购买该课程的折扣信息
        Activite activite = activiteService.getOne(Wrappers.<Activite>lambdaQuery().eq(Activite::getId, contract.getActivityId()));

        //折扣
        Double discount = activite.getDiscount();
        //优惠券
        Integer vouchers = activite.getVouchers();

        //合同的金额
        Double orders =  null;
        //1 是折扣 2是代金券 先判断拿到的优惠卷是不是有效的
        if (activite.getStatus() == Valid ){
            //判断活动优惠的类型 1 是折扣 2是代金券
            if (activite.getType().equals(1)){
                orders = price * discount * 0.1;
            } else if (activite.getType().equals(2)){
                //优惠券
                orders = price - vouchers;
            }
        } else {
            //优惠卷和折扣都是无效的
            orders = price;
        }
        contract.setCoursePrice(price);
        contract.setOrders(orders);
        contract.setDiscountType(activite.getType()+"");
        contract.setUpdateTime(new Date());
        contract.setUpdateBy(SecurityUtils.getUsername());

        boolean flag = super.updateById(contract);
        return flag;
    }

    @Override
    public ContractDeatilsVo getContractDetails(Integer id) {
        Contract contract = super.getById(id);
        ContractDeatilsVo contractDeatilsVo = new ContractDeatilsVo();

        org.springframework.beans.BeanUtils.copyProperties(contract,contractDeatilsVo);
        contractDeatilsVo.setOrder(contract.getOrders());

        contractDeatilsVo.setId(contract.getId()+"");
        contractDeatilsVo.setSubject(contract.getSubject()+"");
        contractDeatilsVo.setChannel(contract.getChannel()+"");
        contractDeatilsVo.setStatus(contract.getStatus()+"");

        contractDeatilsVo.setCreateBy("admin");
        contractDeatilsVo.setUpdateBy("admin");
        return contractDeatilsVo;
    }

    /**
     * 获取合同收入
     * @param id
     * @return
     */
    @Override
    public Integer getActiAmountById(Long id) {
        Integer amount = contractMapper.getActiAmountById(id);
        return amount;
    }



    /**
     * 开始检查合同的状态
     * 合同状态 0：无效 1有效
     */
    public void executeContract() {
        List<Contract> contractList = super.list();
        //为空直接返回
        if (CollectionUtils.isEmpty(contractList)){
            return;
        }
        for (Contract contract : contractList) {
            //判断当前时间是不是在合同finishTime内
            if (LocalDateTime.now().isAfter(contract.getFinishTime())){
                //合同已过期
                contract.setStatus(CONTRACT_NOT_START);
            } else {
                //当前时间还没到 finishTime
                contract.setStatus(CONTRACT_START);
            }
        }
    }


}




